package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"order_srv/cache"
	"order_srv/models"
	"order_srv/pkg"
	"strconv"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订单创建
func (l *CreateOrderLogic) CreateOrder(in *order.CreateOrderRequest) (*order.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line
	var err error

	//判断商品是否存在
	var goods models.Goods
	goods.ID = uint(in.GoodsId)
	err = goods.Detail()
	if err != nil {
		logx.Error("获取商品详情失败")
		return nil, errors.New("获取商品详情失败")
	}

	//判断库存是否充足
	stock, _ := cache.GetGoodsStock(int(in.GoodsId))
	if stock < in.Num {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}

	//扣减库存
	cache.DecrGoodsStock(int(in.GoodsId), int(in.Num))

	//生成订单
	orderSn := uuid.NewString()
	amount := goods.GoodsPrice * float64(in.Num)
	o := models.Order{
		UserId:  int(in.UserId),
		OrderSn: orderSn,
		Amount:  amount,
	}

	err = o.Create()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}

	//生成订单商品
	og := models.OrderGoods{
		OrderId:    int(o.ID),
		GoodsId:    int(in.GoodsId),
		GoodsTitle: goods.GoodsTitle,
		GoodsNum:   int(in.Num),
		GoodsPrice: goods.GoodsPrice,
	}
	err = og.Create()
	if err != nil {
		logx.Error("订单商品创建失败")
		return nil, errors.New("订单商品创建失败")
	}

	//生成支付链接
	payUrl := pkg.Alipay(orderSn, strconv.Itoa(int(amount)))

	//返回支付连接
	return &order.CreateOrderResponse{
		PayUrl: payUrl,
	}, nil
}
